<template>
  <div class="chat-container">
    <div class="chat-messages" ref="messageContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="message.sender === 'user'? 'user-message' : 'customer-service-message'"
      >
        <span class="message-sender">{{ message.sender }}</span>
        <span class="message-content">{{ message.content }}</span>
      </div>
    </div>
    <div class="chat-input">
      <input
        v-model="newMessage"
        placeholder="输入消息"
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import type { Message } from '../utils/type';

export default defineComponent({
  name: 'ChatComponent',
  setup() {
    const messages = ref<Message[]>([]);
    const newMessage = ref('');
    const sendMessage = () => {
      if (newMessage.value.trim()) {
        // 创建用户发送的消息对象
        const userMessage: Message = {
          sender: 'user',
          content: newMessage.value
        };
        messages.value.push(userMessage);
        // 这里可以添加代码，比如发送网络请求将消息发送给客服系统，并接收客服回复
        // 为了简单示例，模拟客服回复
        const customerServiceReply: Message = {
          sender: '维度健康',
          content: `客服回复：已收到您的消息“${newMessage.value}”，正在处理哦~`
        };
        setTimeout(() => {
          messages.value.push(customerServiceReply);
          // 滚动到最新消息
          const messageContainer = document.querySelector('.chat-messages');
          if (messageContainer) {
            messageContainer.scrollTop = messageContainer.scrollHeight;
          }
        }, 1000);

        newMessage.value = '';
      }
    };

    return {
      messages,
      newMessage,
      sendMessage
    };
  }
});
</script>

<style scoped lang="scss">
.chat-container {
  width: 50%;
  height: 44vh;
  border: 0.5px solid #ccc;
  margin: 0 auto;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  padding: 5px;
  overflow-y: auto;
}

.user-message {
  text-align: right;
  background-color: #e0f7fa;
  border-radius: 5px;
  padding: 2.5px 5px;
  margin-bottom: 2.5px;
}

.customer-service-message {
  text-align: left;
  background-color: #c8e6c9;
  border-radius: 5px;
  padding: 2.5px 5px;
  margin-bottom: 2.5px;
}

.message-sender {
  font-weight: bold;
  font-size: 0.5em; /* 假设原本字体大小为1em，缩小50% */
}

.chat-input {
  display: flex;
  padding: 5px;
  border-top: 0.5px solid #ccc;
}

.chat-input input {
  flex: 1;
  margin-right: 5px;
  padding: 2.5px;
}

.chat-input button {
  padding: 2.5px 5px;
}
</style>
